/*
 * @(#)MaintDmsTiffVierwerAction
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.dms.web;

/**
 * MaintDmsTiffVierwerAction
 * 
 * This class is for maint dms dmsDocument action
 * 
 * @author barbin
 * @company DCIVision Limited
 * @creation date 20060831
 * @version $Revision: 1.3.2.2 $
 */

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.dcivision.alert.bean.UpdateAlert;
import com.dcivision.alert.core.AdapterMaster;
import com.dcivision.alert.core.AlertManager;
import com.dcivision.audit.AuditTrailConstant;
import com.dcivision.audit.core.AuditTrailManager;
import com.dcivision.dms.DmsOperationConstant;
import com.dcivision.dms.bean.DmsDocument;
import com.dcivision.dms.bean.DmsVersion;
import com.dcivision.dms.bean.MtmDocumentRelationship;
import com.dcivision.dms.core.DocumentOperationManager;
import com.dcivision.dms.core.DocumentRetrievalManager;
import com.dcivision.dms.core.VersionControlManager;
import com.dcivision.dms.dao.MtmDocumentRelationshipDAObject;
import com.dcivision.framework.AdapterMasterFactory;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.SystemParameterConstant;
import com.dcivision.framework.SystemParameterFactory;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.framework.web.AbstractMaintAction;

public class MaintDmsTiffVierwerAction extends AbstractMaintAction {
	
  public String getFunctionCode() {
		return (SystemFunctionConstant.DMS_PUBLIC_FOLDER);
	}

	
  public String getMajorDAOClassName() {
		return null;
	}

	
  public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws ServletException {
		SessionContainer sessionContainer = this.getSessionContainer(request);
		Connection conn = this.getConnection(request);
		DmsDocument document = null;
		DmsVersion dmsVersion = new DmsVersion();
		DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(
				sessionContainer, conn);
		DocumentOperationManager documentOperationManager = new DocumentOperationManager(
				sessionContainer, conn);
		String annotationName = "annotation.xml";
		try {
			// open the tiff document
			if (request.getParameter("isFirstView") != null) {
				boolean isHasRight = true;
				DmsDocument annotationDocument = null;
				Integer documentID = TextUtility.parseIntegerObj(request
						.getParameter("documentID"));
				String version = request.getParameter("version");
				Integer versionID = new Integer(1);
				String sCurFunctionCode = docRetrievalManager
						.getCurFunctionCode(docRetrievalManager
								.getDocument(documentID));
				document = docRetrievalManager.getDocument(documentID);
				String path = docRetrievalManager.getLocationPath(document
						.getParentID());
				if ((!document.getItemStatus().equals("A"))
						&& (!sCurFunctionCode.equals("DMS_PERSONAL_FOLDER"))) {
					isHasRight = false;
				}
				// get tiff file annotation xml . if get null then create a new document
				annotationDocument = docRetrievalManager
						.getDocumentByNameParentID(annotationName, document.getID());
				if (annotationDocument == null) {
					String annotationContent = "<Annotation/>";
					DmsDocument doc = new DmsDocument();
					doc.setDocumentName(annotationName);
					doc.setParentID(document.getID());
					doc.setOwnerID(sessionContainer.getUserRecordID());
					doc.setRootID(document.getRootID());
					
					doc.setDocumentType(DmsDocument.TIF_ANNOTATION_TYPE);
					doc.setCreateType(DmsOperationConstant.DMS_CREATE_BY_SYSTEM);
					doc.setRecordStatus(GlobalConstant.RECORD_STATUS_ACTIVE);
					doc.setItemSize(new Integer(annotationContent.length()));
					InputStream inputStream = new ByteArrayInputStream(annotationContent
							.getBytes());
					// create default annotation xml file for current document
					annotationDocument = documentOperationManager.createDocument(doc,
							inputStream);
					conn.commit();
				}

				if (!Utility.isEmpty(version)
						&& !DmsOperationConstant.DMS_TOP_VERSION.equals(version)) {
					versionID = TextUtility.parseIntegerObj(version);
					dmsVersion = docRetrievalManager
							.getVersionByVersionID(versionID);
				} else if (DmsOperationConstant.DMS_TOP_VERSION.equals(version)) {
					dmsVersion = docRetrievalManager
							.getTopVersionByDocumentID(documentID);
				}

				// set arguments for open current tiff document. return current tiff
				// document view
				String appPath = SystemParameterFactory
						.getSystemParameter(SystemParameterConstant.APPLICATION_BASE_URL);
				request.setAttribute("path", appPath);
				request.setAttribute("isHasRight", new Boolean(isHasRight).toString());
				request.setAttribute("documentID", document.getID());
				request.setAttribute("documentName", document.getDocumentName());
				request
						.setAttribute("annotationDocumentID", annotationDocument.getID());
				request.setAttribute("rootID", document.getRootID());
				request.setAttribute("isSaveOk", new Boolean(false).toString());

				if (request.getParameter("isFirstView") != null) {
					// Alert Manager
					AdapterMaster am = AdapterMasterFactory.getAdapterMaster(
							sessionContainer, conn);
					try {
						log.debug("call AM!!!!!");
						log.debug("newDmsDocument.getDocumentName() is "
								+ document.getDocumentName());
						am.call(UpdateAlert.DOCUMENT_TYPE, document.getID(),
								UpdateAlert.VIEW_ACTION, document.getDocumentName(), null,
								null, null);
						if (docRetrievalManager.hasRelationship(document.getID(), null)) {
							MtmDocumentRelationshipDAObject docRelationshipDAO = new MtmDocumentRelationshipDAObject(
									sessionContainer, conn);
							List relationList = docRelationshipDAO
									.getListByIDRelationType(document.getID(), null);
							List inRelationList = docRelationshipDAO
									.getListByRelationIDRelationType(document.getID(), null);
							List alertList = new ArrayList();
							AlertManager alertManager = new AlertManager(sessionContainer,
									conn);
							if (!Utility.isEmpty(relationList)) {
								for (int i = 0; i < relationList.size(); i++) {
									alertList = alertManager
											.listUpdateAlertByObjectTypeObjectIDAndAction(
													UpdateAlert.DOCUMENT_TYPE,
													((MtmDocumentRelationship) relationList.get(i))
															.getDocumentID(), UpdateAlert.MODIFY_RELATED_DOC);
									if (!Utility.isEmpty(alertList)) {
										am.call(UpdateAlert.DOCUMENT_TYPE,
												((MtmDocumentRelationship) relationList.get(i))
														.getDocumentID(), UpdateAlert.MODIFY_RELATED_DOC,
												document.getDocumentName(), null, null, null, document
														.getID());
									}
								}
							}
							if (!Utility.isEmpty(inRelationList)) {
								for (int i = 0; i < inRelationList.size(); i++) {
									alertList = alertManager
											.listUpdateAlertByObjectTypeObjectIDAndAction(
													UpdateAlert.DOCUMENT_TYPE,
													((MtmDocumentRelationship) inRelationList.get(i))
															.getRelatedDocumentID(),
													UpdateAlert.MODIFY_RELATED_DOC);
									if (!Utility.isEmpty(alertList)) {
										am.call(UpdateAlert.DOCUMENT_TYPE,
												((MtmDocumentRelationship) inRelationList.get(i))
														.getRelatedDocumentID(),
												UpdateAlert.MODIFY_RELATED_DOC, document
														.getDocumentName(), null, null, null, document
														.getID());
									}
								}
							}
						}
						log.debug("finished AM!!!!!");
					} catch (Exception e) {
            log.error(e, e);
					}

					// log down in audit trail
					AuditTrailManager auditManager = new AuditTrailManager(
							sessionContainer, conn);
					if (sessionContainer.getUserRecordID() != null) {
						auditManager.auditTrail(GlobalConstant.OBJECT_TYPE_DOCUMENT,
								document, AuditTrailConstant.ACCESS_TYPE_VIEW, dmsVersion
										.getVersionNumber());
					}
				}
			} else {
				// get annotation content from page when submit
				String annotationContent = request.getParameter("HField");
				Integer parentID = TextUtility.parseIntegerObj(request
						.getParameter("parentID"));
				String rootID = request.getParameter("rootID");
				Integer documentID = TextUtility.parseIntegerObj(request
						.getParameter("documentID"));
				DmsVersion version = docRetrievalManager
						.getTopVersionByDocumentID(documentID);
				InputStream inputStream = new ByteArrayInputStream(annotationContent
						.getBytes());
				VersionControlManager versionControlManager = new VersionControlManager(
						sessionContainer, conn);
				DmsDocument doc = docRetrievalManager
						.getDocument(documentID);
				document = docRetrievalManager.getDocument(parentID);
				String sCurFunctionCode = docRetrievalManager.getCurFunctionCode(doc);
				if (!sCurFunctionCode.equals("DMS_PERSONAL_FOLDER")) {
					// if this annotation xml file's functionCode is public folder .first
					// checkout it;
					versionControlManager
							.checkoutDocument(DmsVersion.EXCLUSIVE_LOCK, doc);
					conn.commit();
				}

				// checkin this annotation xml file
				versionControlManager.checkinDocumentName(true,
						DmsVersion.AVAILABLE_STATUS, documentID, version, inputStream,
						annotationName);
				conn.commit();

				try {
					// release resource
					sessionContainer = null;
					versionControlManager.release();
					docRetrievalManager.release();
				} catch (Exception e) {
          log.error(e, e);
				} finally {
					conn = null;
				}

				// set arguments for open current tiff document. return current tiff
				// document view
				String appPath = SystemParameterFactory
						.getSystemParameter(SystemParameterConstant.APPLICATION_BASE_URL);
				request.setAttribute("path", appPath);
				request.setAttribute("isHasRight", new Boolean(true).toString());
				request.setAttribute("documentID", parentID);
				request.setAttribute("documentName", document.getDocumentName());
				request.setAttribute("annotationDocumentID", doc.getID());
				request.setAttribute("rootID", doc.getRootID());
				request.setAttribute("isSaveOk", new Boolean(true).toString());
			}
		} catch (Exception e) {
      log.error(e, e);
		}
		return mapping.findForward("V");
	}

}
